package cn.johnyu.base.controller;

import cn.johnyu.base.dao.CustomerMapper;
import cn.johnyu.base.model.Customer;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;


@RestController
public class AuthController {
    @Autowired
    private CustomerMapper customerMapper;
    @GetMapping("/login")
    public ResponseEntity<Customer> login(@RequestParam("email") String email, @RequestParam("password") String password, HttpServletRequest request){
        Customer customer = customerMapper.findCustomerByEmail(email);
        if (customer != null && customer.getPassword().equals(password)) {
            request.getSession().setAttribute("customer", customer);
            return ResponseEntity.ok(customer);
        }
        return ResponseEntity.notFound().build();
    }
    @GetMapping("/logout")
    public void logout(HttpServletRequest request){
        request.getSession().invalidate();
    }
    @GetMapping("/isLogin")
    public void isLogin(HttpServletRequest request,HttpServletResponse response){
        HttpSession session = request.getSession();
        if(session==null || session.getAttribute("customer")==null){
            response.setStatus(401);
        }
        else{
            response.setStatus(200);
        }
    }
}
